import pymysql as mysql
import json


class DBConfigError(Exception):
    pass


def _load_config() ->dict:
    from os import path
    try:
        with open(f'{path.dirname(__file__)}/db.json') as f:
            config = json.load(f)
    except Exception:
        raise DBConfigError('数据库配置文件加载出错!')
    return config


# 数据库实例表
_db = {}


class _DB:
    CONFIG = _load_config()

    def __init__(self, name: str):
        self.name = name
        self.conn = mysql.connect(_DB.CONFIG['host'], _DB.CONFIG['user'], _DB.CONFIG['password'], name, charset='utf8mb4')
        self.db = self.conn
        self.cursor = self.db.cursor()
        self.handle = 1

    def close(self):
        self.handle = self.handle - 1
        if self.handle == 0:
            self.conn.close()
            if self.name in _db:
                del _db[self.name]


def connect(name: str):
    if name not in _db:
        db = _DB(name)
        _db[name] = db,
    else:
        db = _db[name]
        db.handle = db.handle + 1
    return db
